<template>
    <div class="flex">
        <el-upload v-model:file-list="fileList" class="upload-demo" :action="action" :multiple="multiple"
            :headers="headers" :limit="limit" :before-remove="beforeRemove" :before-upload="handleBeforeUpload"
            :on-remove="handleOnRemove" :on-success="handleOnSuccess" :on-exceed="handleExceed" accept=".mp4">
            <div class="flex"></div>
            <el-button size="large" type="primary" :icon="VideoCamera">选择视频文件</el-button>
            <template #tip>
                <span class="tip">
                    视频时长10s-60s ，大小不超100M
                </span>
            </template>
        </el-upload>
    </div>
</template>
<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoCamera } from '@element-plus/icons-vue'
import baseurl from '@/api/env.ts'
const props = defineProps({
    multiple: {
        type: Boolean,
        default: false
    },
    limit: {
        type: Number,
        default: 5
    },
    limitSize: {
        type: Number,
        default: 50
    },
    apiPath: {
        type: String,
        default: '/rest/period-insur/serve-company/upload'
    }
})
const emits = defineEmits('update:modelValue')

const action = computed(() => {
    return baseurl + props.apiPath
})
const headers = computed(() => {
    return {
        Authorization: 'Bearer ' + sessionStorage.getItem('token') || ''
    }
})

const fileList = ref([])

const handleBeforeUpload = (file) => {
    console.log(2121, file)
    if (file.type !== 'video/mp4') {
        ElMessage.error('请上传格式为mp4的视频文件')
        return false
    }
    if (file.size > props.limitSize * 1024 * 1024) {
        ElMessage.error(`请上传小于${props.limitSize}M的视频`)
        return false
    }
    return true
}

const handleOnSuccess = (res) => {
    if (res.code === 200 && res.data) {
        emitData()
    }
}

const handleOnRemove = (file) => {
    emitData()
}

const emitData = () => {
    if (fileList.value.length) {
        const res = fileList.value.map(i => {
            const map = {
                name: i.name,
                size: i.size,
                url: i?.response?.data?.fileUrl || '',
                fileUrl: i?.response?.data?.fileUrl || '',
                fileType: i?.raw?.type || 'video'
            }
            return map
        })
        console.log(111, res)
        emits('update:modelValue', res)
    } else {
        emits('update:modelValue', [])
    }
}
</script>
<style lang="scss" scoped>
.tip {
    display: inline-block;
    font-size: 14px;
    color: #BAC0CF;
    margin-left: 20px;
    vertical-align: sub;
}
</style>